package com.example.teacher.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.RdsConstants;
import com.example.common.domain.pojo.Handouts;
import com.example.common.utils.CacheClient;
import com.example.teacher.Service.HandoutsService;
import com.example.teacher.mapper.HandoutsMapper;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class HandoutsServiceImpl extends ServiceImpl<HandoutsMapper, Handouts> implements HandoutsService {

    @Autowired
    private HandoutsMapper handoutsMapper;
    @Autowired
    private CacheClient cacheClient;

//    @Override
//    public Handouts getHandoutsById(String HandoutsId){
//        return handoutsMapper.selectById(HandoutsId);
//    }

    @Override
    public Handouts getHandoutsById(String id) {
        // 使用逻辑过期策略获取讲义信息
        return cacheClient.queryWithLogicalExpire(
                RdsConstants.HANDOUTS_INFO,
                id,
                Handouts.class,
                this::getById, // 使用MyBatis-Plus的基础方法
                RdsConstants.CACHE_NULL_TTL,
                TimeUnit.MINUTES,
                false
        );
    }

    @Override
    public void saveHandouts(Handouts handouts) {
        handoutsMapper.insert(handouts);
    }

    @Override
    public void updateHandouts(Handouts handouts) {
        // 参数校验：确保主键存在
        if (handouts.getId() == null) {
            log.warn("更新讲义时必须提供id");
            throw new IllegalArgumentException("更新讲义时必须提供id");
        }
        // 构建UpdateWrapper
        UpdateWrapper<Handouts> updateWrapper = new UpdateWrapper<>();
        // 设置更新条件（主键）
        updateWrapper.lambda()
                .eq(Handouts::getId, handouts.getId());
        // 动态设置需要更新的字段（只更新非null值）
        LambdaUpdateWrapper<Handouts> lambdaUpdate = updateWrapper.lambda();
        if (handouts.getTitle() != null) {
            lambdaUpdate.set(Handouts::getTitle, handouts.getTitle());
        }
        if (handouts.getUrl() != null) {
            lambdaUpdate.set(Handouts::getUrl, handouts.getUrl());
        }
        // 执行更新操作
        int rows = handoutsMapper.update(null, updateWrapper);
        // 检查更新结果
        if (rows == 0) {
            log.error("更新讲义失败，未找到记录，id={}");
            throw new EntityNotFoundException("未找到对应讲义记录，id=" + handouts.getId());
        }
    }


}
